//
//  GeneralWebViewViewController.m
//  Btpin
//
//  Created by Vic on 2019/4/16.
//  Copyright © 2019 Vic. All rights reserved.
//

#import "GeneralWebViewViewController.h"
#import <WebKit/WebKit.h>
#import "LYWithdrawController.h"
#import "CompanyJobPostedViewController.h"
#import "LYJobHuntingController.h"
#import "InterviewBaseinfoJobModel.h"
#import "CompanyTabBarController.h"
#import "PersonalTabBarController.h"
#import "JobDetailViewController.h"


#import "PMineInviteFriendViewController.h"


@interface GeneralWebViewViewController () <WKNavigationDelegate, WKUIDelegate>
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) UIProgressView *progressView;
@end

@implementation GeneralWebViewViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *title = @"";
    NSString *url = @"";
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [rightBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    rightBtn.hidden = YES;
    [rightBtn addTarget:self action:@selector(rightBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    switch (self.showType) {
        case GeneralWebViewTypeOfNews : {
            title = @"新闻资讯";
            url = self.url;
        } break;
        case GeneralWebViewTypeOfNewsFlash: {
            title = @"";
            url = self.url;
        } break;
        case GeneralWebViewTypeOfGeneralize : {
            title = @"职位推广";
            url = [NSString stringWithFormat:@"https://api.btpin.com/h5/company/jobs_promote?app_version=%@&token=%@", [UIToolsControl getVersionAndBuild], UD_GetOForK(isToken)];
        } break;
        case GeneralWebViewTypeOfIntegrityEmployer : {
            title = @"诚信雇主";
            url = [NSString stringWithFormat:@"https://api.btpin.com/h5/company/integrity_union?app_version=%@&token=%@", [UIToolsControl getVersionAndBuild], UD_GetOForK(isToken)];
        } break;
        case GeneralWebViewTypeOfInviteFriend : {
            title = @"邀请好友";
            url = [NSString stringWithFormat:@"https://api.btpin.com/h5/user/invite_act?app_version=%@&token=%@", [UIToolsControl getVersionAndBuild], UD_GetOForK(isToken)];
        } break;
        case GeneralWebViewTypeOfCreditEvaluation : {
            title = @"";
            url = @"";
        } break;
        case GeneralWebViewTypeOfCoach : {
            rightBtn.hidden = NO;
            [rightBtn setTitle:@" 服务流程" forState:UIControlStateNormal];
            [rightBtn setImage:[UIImage imageNamed:@"wen-shuoming"] forState:UIControlStateNormal];
            rightBtn.frame = CGRectMake(0, 0, 90, 40);
            title = @"求职教练";
            url = [NSString stringWithFormat:@"https://api.btpin.com/h5/personal/job_coach?app_version=%@&token=%@", [UIToolsControl getVersionAndBuild], UD_GetOForK(isToken)];
        } break;
        case GeneralWebViewTypeOfHeadhunting : {
            title = @"猎头服务";
            url = [NSString stringWithFormat:@"https://api.btpin.com/h5/personal/headhunt?app_version=%@&token=%@", [UIToolsControl getVersionAndBuild], UD_GetOForK(isToken)];
        } break;
        case GeneralWebViewTypeOfPrivacyPolicy : {
            title = @"隐私政策";
            url = [NSString stringWithFormat:@"https://api.btpin.com/h5/user/private_policy?app_version=%@&token=%@", [UIToolsControl getVersionAndBuild], UD_GetOForK(isToken)];
        } break;
        case GeneralWebViewTypeOfResignAgreement : {
            title = @"服务协议";
            url = [NSString stringWithFormat:@"https://api.btpin.com/h5/user/agreement?app_version=%@&token=%@", [UIToolsControl getVersionAndBuild], UD_GetOForK(isToken)];
        } break;
        case GeneralWebViewTypeOfWithdrawalInstructions : {
            title = @"提现说明";
            url = [NSString stringWithFormat:@"https://api.btpin.com/h5/page/withdraw_help?app_version=%@&token=%@", [UIToolsControl getVersionAndBuild], UD_GetOForK(isToken)];
        } break;
        case GeneralWebViewTypeOfMakeMoneyExplain: {
            title = @"赚钱说明";
            url = [NSString stringWithFormat:@"https://api.btpin.com/h5/page/job_share_promote_help?app_version=%@&token=%@", [UIToolsControl getVersionAndBuild], UD_GetOForK(isToken)];
        } break;
        case GeneralWebViewTypeOfNotice : {
            title = @"官方通知";
            url = self.url;
        } break;
        default:
            break;
    }
    
    self.navigationItem.title = title;
    
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-HeightOfStatusBarAndNavigationBar-(self.showTabBar?HeightOfTabBar:SIMEmojKeyBoardkBottomNOSafeArea_Height))];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
    self.webView.allowsBackForwardNavigationGestures = YES;
    [self.view addSubview:self.webView];
    
//    [webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
//        //1）获取默认userAgent：
//           NSString *oldUA = result;   //直接获取为nil
//        //2）设置userAgent：添加额外的信息
//          NSString *newUA = [NSString stringWithFormat:@"%@ btpin/(%@)", oldUA , [UIToolsControl getVersionAndBuild]];
//          NSDictionary *dictNU = [NSDictionary dictionaryWithObjectsAndKeys:newUA, @"UserAgent", nil];
//          [[NSUserDefaults standardUserDefaults] registerDefaults:dictNU];
//    }];
    
//    decisionHandler(WKNavigationActionPolicyCancel);
//    [mutableRequest setValue:[NSString stringWithFormat:@"btpin/(%@)", oldUA , [UIToolsControl getVersionAndBuild]] forHTTPHeaderField:@"User-Agent"];
//    [webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError * error) {
//        NSString *newUA = @"***";
//        webView.customUserAgent = newUA;
//        [webView loadRequest:mutableRequest];
//    }];
    
    __weak __typeof(self)weakSelf = self;
    [self.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSString *userAgent = result;
        NSString *newUserAgent = [userAgent stringByAppendingString:[NSString stringWithFormat:@"btpin/%@", [UIToolsControl getVersionAndBuild]]];
        [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent":newUserAgent}];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [strongSelf.webView setCustomUserAgent:newUserAgent];
    }];
    
    
    //TODO:kvo监听，获得页面title和加载进度值
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
}
- (UIProgressView *)progressView {
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 2)];
        _progressView.progressTintColor = THEMECOLOR_OF_ORANGE;
        _progressView.backgroundColor = THEMECOLOR_OF_TEXT_cccccc;
        _progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
        [self.view addSubview:self.progressView];
    }
    return _progressView;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        if (object == self.webView) {
            self.progressView.progress = self.webView.estimatedProgress;
            if (self.progressView.progress == 1) {
                __weak __typeof(self)weakSelf = self;
                [UIView animateWithDuration:0.5f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^ {
                    weakSelf.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.4f);
                } completion:^(BOOL finished) {
                    weakSelf.progressView.hidden = YES;
                }];
            }
        } else {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    } else if ([keyPath isEqualToString:@"title"]) {
        if (object == self.webView) {
            self.navigationItem.title = self.webView.title;
        } else {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    self.progressView.hidden = NO;
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    [self.view bringSubviewToFront:self.progressView];
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    self.progressView.hidden = YES;
}
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    if (error.code==NSURLErrorCancelled) {
        [self webView:webView didFinishNavigation:navigation];
    } else {
        self.progressView.hidden = YES;
    }
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    self.progressView.hidden = YES;
    SVPHUDError(@"加载失败");
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(nonnull WKNavigationAction *)navigationAction decisionHandler:(nonnull void (^)(WKNavigationActionPolicy))decisionHandler {
    //    1.拦截请求
    NSString *urlString = [navigationAction.request.URL absoluteString];
//    if (navigationAction.navigationType == WKNavigationTypeLinkActivated) {
//        跳转别的应用如系统浏览器 对于跨域，需要手动跳转
//        [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
//        // 不允许web内跳转
//        decisionHandler(WKNavigationActionPolicyCancel);
//    } else
    if ([urlString containsString:@"btpin://share?"]) { // 分享 btpin://share?type=1&title=xxx&link=xxx&thumb=xxx&desc=xxx
        decisionHandler(WKNavigationActionPolicyCancel);
        
        NSDictionary *dic = [UIToolsControl getParamsWithUrlString:urlString];
        NSString *type = [UIToolsControl URLDecodedString:dic[@"type"]];
        NSString *title = [UIToolsControl URLDecodedString:dic[@"title"]];
        NSString *link = [UIToolsControl URLDecodedString:dic[@"link"]];
        NSString *thumb = [UIToolsControl URLDecodedString:dic[@"thumb"]];
        NSString *desc = [UIToolsControl URLDecodedString:dic[@"desc"]];
        if ([type isEqualToString:@"1"]) { // 微信好友
            if (![UIToolsControl canOpenWXApp]) {
                SVPHUDError(@"您未安装微信，请先安装");
                return;
            }
            [UIToolsControl wxShareWebURL:link title:title desc:desc thumbUrl:thumb shareType:ShareTypeOfWXHaoyou];
        } else if ([type isEqualToString:@"2"]) { // 朋友圈
            if (![UIToolsControl canOpenWXApp]) {
                SVPHUDError(@"您未安装微信，请先安装");
                return;
            }
             [UIToolsControl wxShareWebURL:link title:title desc:desc thumbUrl:thumb shareType:ShareTypeOfWXPengyouquan];
        } else if ([type isEqualToString:@"3"]) { // QQ
            if (![UIToolsControl canOpenQQApp]) {
                SVPHUDError(@"您未安装QQ，请先安装");
                return;
            }
            [UIToolsControl qqShareWebURL:link title:title desc:desc thumbUrl:thumb shareType:ShareTypeOfQQ];
        } else if ([type isEqualToString:@"4"]) { // QQ空间
            if (![UIToolsControl canOpenQQApp]) {
                SVPHUDError(@"您未安装QQ，请先安装");
                return;
            }
            [UIToolsControl qqShareWebURL:link title:title desc:desc thumbUrl:thumb shareType:ShareTypeOfQQZone];
        }
    } else if ([urlString containsString:@"btpin://redirect?"]) {
        // 指定页面 btpin://redirect?page=withdraw my_jobs-我发布的职位列表页面withdraw-提现页面
        decisionHandler(WKNavigationActionPolicyCancel);
        NSDictionary *dic = [UIToolsControl getParamsWithUrlString:urlString];
        NSString *page = [UIToolsControl URLDecodedString:dic[@"page"]];
        if ([page isEqualToString:@"my_jobs"]) { // 发布职位
            CompanyJobPostedViewController *jobVC = [[CompanyJobPostedViewController alloc] init];
            jobVC.add = ^(BOOL addFlag){
                
            };
            [self.navigationController pushViewController:jobVC animated:YES];
        } else if ([page isEqualToString:@"withdraw"]) { // 提现
            LYWithdrawController *withdrawVC = [[LYWithdrawController alloc] init];
            [self.navigationController pushViewController:withdrawVC animated:YES];
        } else if ([page isEqualToString:@"jobs_list"]) { // 职位列表
            [self.navigationController popToRootViewControllerAnimated:NO];
            PersonalTabBarController *tabBarController = (PersonalTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
            tabBarController.selectedIndex = 0;
        } else if ([page isEqualToString:@"resume_list"]) { // 人才列表
            [self.navigationController popToRootViewControllerAnimated:NO];
            CompanyTabBarController *tabBarController = (CompanyTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
            tabBarController.selectedIndex = 0;
        } else if ([page isEqualToString:@"job_detail"]) { // 职位详情
            NSString *job_id = [UIToolsControl URLDecodedString:dic[@"job_id"]];
            if (job_id && job_id.length) {
                JobDetailViewController *JDVC = [[JobDetailViewController alloc] init];
                JDVC.id = job_id;
                JDVC.showSettingFlag = NO;
                JDVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:JDVC animated:YES];
            }
        }
    } else if ([urlString containsString:@"btpin://open_service?"]) { // 开通服务页 btpin://open_service?service_alias=job_coach&setmeal_id=15
        decisionHandler(WKNavigationActionPolicyCancel);
        NSDictionary *dic = [UIToolsControl getParamsWithUrlString:urlString];
        NSString *service_alias = [UIToolsControl URLDecodedString:dic[@"service_alias"]];
        NSString *setmeal_id = [UIToolsControl URLDecodedString:dic[@"setmeal_id"]];
        if ([service_alias isEqualToString:@"stick_jobs"]) { // 职位置顶
            [self requestListDataWithService_alias:service_alias setmeal_id:setmeal_id];
        } else {
            LYJobHuntingController *jobVC = [[LYJobHuntingController alloc] init];
            jobVC.service_alias = service_alias;
            jobVC.setmeal_id = setmeal_id;
            jobVC.isHtml = YES;
            jobVC.showType = self.showType;
            [self.navigationController pushViewController:jobVC animated:YES];
        }
    }
    else if ([urlString containsString:@"article/detail"]) {
        decisionHandler (WKNavigationActionPolicyCancel);
        if ((self.showType == GeneralWebViewTypeOfNews) || (self.showType == GeneralWebViewTypeOfNewsFlash)) {
            PMineInviteFriendViewController *VC = [[PMineInviteFriendViewController alloc] init];
            VC.url = urlString;
            VC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:VC animated:YES];
        }
    }
    else { // 应用的web内跳转
        decisionHandler (WKNavigationActionPolicyAllow);
    }
    return;//不添加会崩溃
}

- (void)requestListDataWithService_alias:(NSString *)service_alias setmeal_id:(NSString *)setmeal_id {
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    [dic setObject:@"0" forKey:@"status"];
    [dic setObject:@"1" forKey:@"page"];
    [dic setObject:@"1000" forKey:@"number"];
    [BaseNetManager requestWithMethod:POST path:Company_GetJob_Lists_URL params:dic successBlock:^(NSDictionary * _Nonnull responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            NSArray *array = responseObject[@"data"];
            if (array.count) {
                NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:0];
                for (NSDictionary *dic111 in array) {
                    InterviewBaseinfoJobModel *tempModel = [[InterviewBaseinfoJobModel alloc] init];
                    [tempModel setValuesForKeysWithDictionary:dic111];
                    [tempArray addObject:tempModel];
                }
                NSDictionary *dic = array[0];
                LYJobHuntingController *jobVC = [[LYJobHuntingController alloc] init];
                jobVC.service_alias = service_alias;
                jobVC.setmeal_id = setmeal_id;
                jobVC.isHtml = YES;
                jobVC.job_name = dic[@"title"];
                jobVC.job_id = [NSString stringWithFormat:@"%li",[dic[@"id"] integerValue]];
                jobVC.jobArray = tempArray;
                [self.navigationController pushViewController:jobVC animated:YES];
            } else {
                //发布职位
                CompanyJobPostedViewController *jobVC = [[CompanyJobPostedViewController alloc] init];
                jobVC.add = ^(BOOL addFlag){
                    
                };
                [self.navigationController pushViewController:jobVC animated:YES];
            }
        } else {
            SVPHUDError(responseObject[@"msg"]);
        }
    } failurBlock:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark -- Action
- (void)rightBtnClick:(UIButton *)button{
    if (self.showType == GeneralWebViewTypeOfCoach) {
        CustomView *alertView = [[CustomView alloc] initWithTitle:@"服务流程" message:@"1. 请选择会员服务类型，在线支付成功后。\n2. 请您将简历发送至btpin@sina.com 邮箱，简历信息必须真实，否则平台拒绝服务，并不退服务费。\n3. 平台收到简历后，第一时间匹配专业顾问与您联系（不超过1天）。\n4. 会员服务说明：初级会员服务时间有效期不超过5个工作日，中级会员服务时间有效期不超过 15个工作日，高级会员服务时间有效期不超过30个工作日。"];
        alertView.resultIndex = ^(NSInteger index){
            //回调---处理一系列动
        };
        [alertView showXLAlertView];
    }
}


#pragma mark 移除观察者
- (void)dealloc {
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView removeObserver:self forKeyPath:@"title"];
}
- (void)customBackButtonTap {
    if (self.webView.canGoBack == YES) {
        [self.webView goBack];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

@end
